<?php
class Rol{
	private $setter;
	private $dbOperator;
	
	private $id;
	private $nombre;
	private $sections;
	private $descripcion;
	
	function Rol(){
		$this->setter=new Setter("../Config");
		$this->dbOperator=new DbOperator($this->setter->getDataBaseHost(),$this->setter->getDataBaseUserName(),$this->setter->getDataBaseName(),$this->setter->getDataBasePassword());
		$this->id="";
		$this->nombre="";
		$this->sections=array();
		$this->descripcion="";
		
	}
	
	function setId($id=""){
		$this->id=$id;
	}
	function getId(){
		return $this->id;
	}
	
	function setSections($sections=array()){
		$this->sections=$sections;
	}
	function getSections(){
		return $this->sections;
	}
	
	function setNombre($nombre=""){
		$this->nombre=$nombre;
	}
	function getNombre(){
		return $this->nombre;
	}
	
	function setDescripcion($descripcion=""){
		$this->descripcion=$descripcion;
	}
	function getDescripcion(){
		return $this->descripcion;
	}
	
	
	function guardar(){
		$this->dbOperator->connect();
		//Guardar en la tabla roles
		$this->dbOperator->dbInsert(array("",$this->nombre,$this->descripcion),"roles");
		
		//guardar en la tabla de permisos-----------------------------------------
		//Hallar el último rol registrado
		$rolUltimo=$this->dbOperator->consult("SELECT MAX(id) FROM roles","yes");
				
		//registrar las secciones a las que tiene derecho en permisos
		foreach($this->sections as $section){
			$this->dbOperator->dbInsert(array("",$rolUltimo[0],$section),"permisos");
		}
		//-------------------------------------------------------------------------
	}
	function eliminar(){
		$this->dbOperator->connect();
		
		//Cambiar roles de usuarios afectados con la eliminación a invitados
		$idInvitado=$this->dbOperator->consult("SELECT id FROM roles WHERE nombre='invitado'","yes");
		$this->dbOperator->consult("UPDATE usuarios SET idRol='".$idInvitado[0]."' WHERE idRol='".$this->id."'");
		//------------------------------------------------------------------
		
		$this->dbOperator->erase("roles","id",$this->id);
		$this->dbOperator->erase("permisos","idRol",$this->id);			
	}
 	function actualizar(){
 		$this->dbOperator->connect();
		$this->dbOperator->dbUpdate(array("descripcion"=>$this->descripcion),"roles","id",$this->id);
 		//-------------------------------
 		$this->dbOperator->erase("permisos","idRol",$this->id);
 	
 		foreach($this->sections as $section){
			$this->dbOperator->dbInsert(array("",$this->id,$section),"permisos");
		}
		
 	}
	function cargar($idRol="0"){
		$this->dbOperator->connect();
		$dataRol=$this->dbOperator->consult("SELECT * FROM roles WHERE id='".$idRol."'","yes");
		$this->id=$dataRol[0];
		$this->nombre=$dataRol[1];
		$this->descripcion=$dataRol[2];
		
		//Cargar las secciones autorizadas
		$this->sections=$this->dbOperator->consult("SELECT seccion FROM permisos WHERE idRol=$this->id", "yes");
	}
}
?>
